package org.catspaw.cherubim.matcher;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.aspectj.weaver.tools.PointcutExpression;
import org.aspectj.weaver.tools.PointcutParser;
import org.aspectj.weaver.tools.ShadowMatch;

/**
 * Method匹配器实现 用AspectJ PointCut表达式匹配目标方法
 * @author 孙宁振
 */
public class SimpleAspectJMethodMatcher implements Matcher<String, Method> {

	/**
	 * 匹配器
	 */
	private PointcutParser					pointcutParser	= PointcutParser
																	.getPointcutParserSupportingAllPrimitivesAndUsingContextClassloaderForResolution();
	private boolean							usePatternCache;
	private Map<String, PointcutExpression>	cache;

	public SimpleAspectJMethodMatcher() {
	}

	public SimpleAspectJMethodMatcher(boolean usePatternCache) {
		this.usePatternCache = usePatternCache;
		if (usePatternCache) {
			cache = new HashMap<String, PointcutExpression>();
		}
	}

	/**
	 * 判断指定资源描述符和指定目标字符串是否匹配
	 * @param pattern 资源描述符
	 * @param method 被匹配方法
	 * @return 是否匹配
	 */
	public boolean match(String pattern, Method method) {
		pattern = "execution(" + pattern + ")";
		PointcutExpression expression = null;
		if (usePatternCache) {
			expression = cache.get(pattern);
		}
		if (expression == null) {
			expression = pointcutParser.parsePointcutExpression(pattern);
			if (usePatternCache) {
				cache.put(pattern, expression);
			}
		}
		ShadowMatch match = expression.matchesMethodExecution(method);
		return match.alwaysMatches();
	}

	public PointcutParser getPointcutParser() {
		return pointcutParser;
	}
}
